<template>
  <div class="blog-toc-container">
    <h2>目录</h2>
    <RightList :list="tocWithSelect" @select="handleSelect" />
  </div>
</template>

<script>
import RightList from "./RightList.vue";
import {debounce} from '@/utils';
export default {
  components: {
    RightList,
  },
  props: {
    toc: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {
      nowAnchor: "article-md-title-1",
    };
  },
  computed: {
    // 根据toc属性以及activeAnchor得到带有isSelect属性的toc数组
    tocWithSelect() {
      const getToc = (toc = []) => {
        return toc.map((t) => ({
          ...t,
          isSelect: this.nowAnchor === t.anchor,
          children: getToc(t.children),
        }));
      };
      return getToc(this.toc);
    },
    // 根据toc得到它们对应的元素数组
    doms() {
      const doms = [];
      const getDom = (toc = []) => {
        for (const t of toc) {
          doms.push(document.getElementById(t.anchor));
          if(t.children && t.children.length) {
            getDom(t.children);
          }
        }
      };
      getDom(this.toc)
      return doms;
    },
  },
  created() {
    // 防抖
    this.setSelectBounce = debounce(this.setSelect)
    this.$bus.$on('mainScroll', this.setSelectBounce)
  },
  destroyed(){ 
    this.$bus.$off('mainScroll', this.setSelectBounce)
  },
  methods: {
    handleSelect(item) {
      location.hash = item.anchor;
    },
     // 设置activeAnchor为正确的值
     setSelect() {
      const range = 200;
      for (const dom of this.doms) {
        if(!dom) {
          // 如果没有dom，则允许下个循环
          continue;
        }
        const top = dom.getBoundingClientRect().top;
        if(top >= 0 && top <= range) {
          // 在此区域内；
          this.nowAnchor = dom.id;
        } else if(top > range) {
          return;
        } else {
          // 如果都没有，先让自己激活，在看后面
          this.nowAnchor = dom.id;
        }
      }
     }
  },
  
};
</script>

<style scoped lang="less">
.blog-toc-container {
  h2 {
    font-weight: bold;
    letter-spacing: 2px;
    font-size: 1em;
    margin: 0;
  }
}
</style>
